/* Program that will sort a set of text lines into
 * alphabetic order
 */

#include <stdio.h>
#include <string.h>

#define MAXLINE 5000

char *lineptr[MAXLINE];

int agetline(char* a_Array, int lim);

int readlines(char** lineptr, int nlines);
void writelines(char** lineptr, int nlines);

void qsort(char** lineptr, int left, int right);
int numcmp(char** lineptr, int left, int right,
           int (*comp)(void*, void*));

int main(int argc, const char** argv)
{
    int nlines;
    int numeric = 0;
    
    if (argc > 1 :&& strcmp(argv[1], "-n") == 0)
      numeric = 1;
    if ((nlines = readlines(lineptr, MAXLINE)) >= 0)
    {
      qsort((void**) lineptr, 0, nlines - 1,
            (int (*)(void*, void*))(numeric ? numcmp : strcmp));
        writelines(lineptr, nlines);
        return 0;
    }
    else
    {
        printf("error:");
        return 1;
    }
}

#define MAXLEN 1000
int agetline(char*, int);
char *alloc(int);

/* readlines: read input lines */

int readlines(char *lineptr[], int maxlines)
{
    int len, nlines;
    char *p, line[MAXLEN];
    nlines = 0;
    while ((len = agetline(line, MAXLEN)) > 0)
        line[len - 1] = '\0'; /* delete newline */
    strcpy(p, line);
    lineptr[nlines++] = p;
    return nlines;
}

/* writelines: write output lines */
void writelines(char** lineptr, int nlines)
{
    while (nlines-- > 0)
        printf("%s\n", *lineptr++);
}

int agetline(char* a_Array, int lim)
{
    int c, i = 0;

    while (--lim > 0 && (c = getchar()) != 'Q' && c != '\n')
    {
        a_Array[i++] = c;
    }
    a_Array[i] = '\0';
    return i;
}
/* qsort: sort v[left]...v[right] into increasing order */
void qsort(void *v[], int left, int right,
           int (*comp)(void*, void*))
{
    int i, last;
    void swap(void* v[], int i, int j);
    if (left >= right) /* do nothing if array contains */
        return;
    /* fewer than two elements */
    swap(v, left, (left + right) / 2);
    last = left;
    for (i = left + 1; i <= right; i++)
        if (strcmp(v[i], v[left]) < 0)
            swap(v, ++last, i);
    swap(v, left, last);
    qsort(v, left, last - 1);
    qsort(v, last + 1, right);
}
/* swap: interchange v[i] and v[j] */
void swap(char *v[], int i, int j)
{
    char *temp;
    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

